/**
 * Copyright (C) 2009 Ignasi Fosch Alonso
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 
 * details.
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * You can reach me by mail at natx@y10k.ws
 * You can reach him by paper mail at:
 * C. LLEIDA, 41-43, 3r 1a
 * El Prat de Llobregat 08820
 * Barcelona, SPAIN
 */
package ws.y10k.goloim.interfaces.swt;

import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import ws.y10k.goloim.model.Order;
import ws.y10k.goloim.model.OrderLine;

/**
 * @author natx
 *
 */
public class OrderWindow extends Window {
	
	Order existingOrder = null;
	Table tblOrderLines;
	private Label lblCode;
	Text txtCode;
	private Label lblCustomer;
	Text txtCustomer;
	Button btnAddOrderLine;
	private Button btnSave;
	private Button btnCancel;

	public OrderWindow(Window parent) {
		super(parent);
		this.setShellStyle(SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
		this.open();
	}
	
	public OrderWindow(Window parent, Order data) {
		this(parent);
		existingOrder = data;
		txtCode.setText(data.getCode());
		txtCode.setEnabled(false);
		txtCustomer.setFocus();
		txtCustomer.setText(data.getCustomer());
		Object[] orderLines = data.getOrderLines();
		for ( int i = 0; i < orderLines.length; i++ ) {
			TableItem item = new TableItem(tblOrderLines,SWT.NONE);
			item.setText(0,((OrderLine) orderLines[i]).getProduct().getReference());
			item.setText(1,((Integer)((OrderLine) orderLines[i]).getQty()).toString());
		}
	}

	public Control createContents(Composite parent) {
		// TODO i18n

		parent.getShell().setSize(300, 300);
		parent.getShell().setText("Add order");
		GoLoIm.center(parent.getShell());
		RowLayout lytRow = new RowLayout();
		parent.getShell().setLayout(lytRow);
		
		Composite cmpForm = new Composite(parent.getShell(), SWT.NULL);
		RowData rdt = new RowData();
		rdt.width = parent.getShell().getBounds().width - 15;
		rdt.height = parent.getShell().getBounds().height - 37;
		cmpForm.setLayoutData(rdt);
		GridLayout lytGridForm = new GridLayout();
		lytGridForm.numColumns = 2;
		cmpForm.setLayout(lytGridForm);
		

		lblCode = new Label(cmpForm,SWT.NONE);
		lblCode.setText("&Code");
		GridData grdData = new GridData();
		grdData.widthHint = 100;
		lblCode.setLayoutData(grdData);
		txtCode = new Text(cmpForm,SWT.BORDER);
		grdData = new GridData();
		grdData.widthHint = parent.getShell().getBounds().width - 100;
		txtCode.setLayoutData(grdData);
		lblCustomer = new Label(cmpForm,SWT.NONE);
		lblCustomer.setText("&Customer");
		grdData = new GridData();
		grdData.widthHint = 100;
		lblCustomer.setLayoutData(grdData);
		txtCustomer = new Text(cmpForm,SWT.BORDER);
		grdData = new GridData();
		grdData.widthHint = parent.getShell().getBounds().width - 100;
		txtCustomer.setLayoutData(grdData);
		
		tblOrderLines = new Table(cmpForm, SWT.BORDER);
		grdData = new GridData();
		grdData.widthHint = parent.getShell().getBounds().width - 40;
		grdData.heightHint = parent.getShell().getBounds().height - 175;
		grdData.horizontalSpan = 2;
		tblOrderLines.setLayoutData(grdData);
		tblOrderLines.setLocation(0,150);
		tblOrderLines.setLinesVisible(true);
		tblOrderLines.setHeaderVisible(true);
		TableColumn col = new TableColumn(tblOrderLines,SWT.NONE);
		col.setText("Product ref");
		col.setWidth(parent.getShell().getBounds().width / 2);
		TableColumn col2 = new TableColumn(tblOrderLines,SWT.NONE);
		col2.setText("Qty");
		for ( int i = 0; i < tblOrderLines.getColumnCount(); i++ ) {
			tblOrderLines.getColumn(i).pack();
		}
		final TableEditor editor = new TableEditor (tblOrderLines);
		editor.horizontalAlignment = SWT.LEFT;
		editor.grabHorizontal = true;
		tblOrderLines.addListener(SWT.MouseDoubleClick, new Listener () {
			@Override
			public void handleEvent(Event event) {
				final TableItem item = new TableItem(tblOrderLines, SWT.NONE);
				final Combo cmbProducts = new Combo(tblOrderLines, SWT.READ_ONLY);
				cmbProducts.setItems(GoLoIm.products.getStringArray());
				Listener cmbListener = new Listener () {
					public void handleEvent(final Event e) {
						switch (e.type) {
						case SWT.Selection:
							item.setText(0, cmbProducts.getItem(cmbProducts.getSelectionIndex()));
							item.setText(1, "0");
							cmbProducts.dispose();
							break;
						}
					}
				};
				cmbProducts.addListener(SWT.Selection, cmbListener);
				editor.setEditor(cmbProducts, item, 0);
				cmbProducts.setFocus();
			}
		});
		tblOrderLines.addListener(SWT.MouseDown, new Listener() {
			@Override
			public void handleEvent(Event event) {
				Rectangle clientArea = tblOrderLines.getClientArea();
				Point pt = new Point(event.x, event.y);
				int index = tblOrderLines.getTopIndex();
				while ( index < tblOrderLines.getItemCount() ) {
					boolean visible = false;
					final TableItem item = tblOrderLines.getItem(index);
					Rectangle rect = item.getBounds(0);
					if ( rect.contains(pt) ) {
						final Combo cmbProducts = new Combo(tblOrderLines, SWT.READ_ONLY);
						cmbProducts.setItems(GoLoIm.products.getStringArray());
						Listener cmbListener = new Listener() {
							public void handleEvent(final Event e) {
								switch (e.type) {
									case SWT.Selection:
										item.setText(0, cmbProducts.getItem(cmbProducts.getSelectionIndex()));
										if ( item.getText(1).length() == 0 ) item.setText(1,"0");
										cmbProducts.dispose();
										break;
								}
							}
						};
						cmbProducts.addListener(SWT.Selection, cmbListener);
						editor.setEditor(cmbProducts, item, 0);
						cmbProducts.setFocus();
						return;
					} else {
						for ( int i=1; i<tblOrderLines.getColumnCount(); i++ ) {
							rect = item.getBounds(i);
							if ( rect.contains(pt) ) {
								final int column = i;
								final Text text = new Text(tblOrderLines, SWT.NONE);
								Listener textListener = new Listener() {
									public void handleEvent(final Event e) {
										switch (e.type) {
											case SWT.FocusOut:
												item.setText(column, text.getText ());
												text.dispose();
												break;
											case SWT.Traverse:
												switch (e.detail) {
													case SWT.TRAVERSE_RETURN:
														item.setText(column, text.getText ());
														// FALL THROUGH
													case SWT.TRAVERSE_ESCAPE:
														text.dispose();
														e.doit = false;
												}
												break;
										}
									}
								};
								text.addListener(SWT.FocusOut, textListener);
								text.addListener(SWT.Traverse, textListener);
								editor.setEditor(text, item, i);
								text.setText(item.getText (i));
								text.selectAll();
								text.setFocus();
								return;
							}
						}
					}
					if ( !visible && rect.intersects(clientArea) ) {
						visible = true;
					}
					if ( !visible ) return;
					index++;
				}
			}
		});

		
		btnSave = new Button(cmpForm, SWT.PUSH);
		grdData = new GridData();
		grdData.widthHint = 100;
		grdData.horizontalAlignment = SWT.CENTER;
		btnSave.setLayoutData(grdData);
		btnSave.setText("&Save");
		btnSave.addSelectionListener(new SaveOrderSelectionListener(this));
		btnCancel = new Button(cmpForm, SWT.PUSH);
		grdData = new GridData();
		grdData.widthHint = 100;
		grdData.horizontalAlignment = SWT.CENTER;
		btnCancel.setLayoutData(grdData);
		btnCancel.setText("&Cancel");
		btnCancel.addSelectionListener(new CancelSelectionListener(parent.getShell()));
		txtCode.setFocus();
		parent.getShell().setDefaultButton(btnCancel);

		return parent;
		
	}

}
